$(function() {
    cateinit();
    initEditor()


    var $image = $('#image')
    var options = {
        aspectRatio: 280 / 400,
        preview: '.img-preview'
    }

    $image.cropper(options);

    $('#chooseimg').on('click', function() {
        $('#choose').click();
    })

    $('#choose').on('change', function(e) {
        var fileList = e.target.files;
        if (fileList.length == 0) {
            return layui.layer.msg('海报不可以为空!');
        }
        var file = e.target.files[0];
        var newImgURL = URL.createObjectURL(file);
        $image
            .cropper('destroy') // 销毁旧的裁剪区域
            .attr('src', newImgURL) // 重新设置图片路径
            .cropper(options) // 重新初始化裁剪区域
    })

    var mv_state = '已上映';
    $('#adv').on('click', function() {
        mv_state = '预售';
    })

    $('#mvinfo').on('submit', function(e) {
        e.preventDefault();
        var fd = new FormData($(this)[0]);
        fd.append('state', mv_state);

        $image
            .cropper('getCroppedCanvas', {
                width: 280,
                height: 400
            })
            .toBlob(function(blob) {
                fd.append('cover_img', blob);
                $.ajax({
                    type: 'POST',
                    url: '/my/movie/addmovie',
                    data: fd,
                    contentType: false,
                    processData: false,
                    success: function(res) {
                        if (res.status != 0) {
                            return layui.layer.msg('电影上线失败！')
                        }
                        layui.layer.msg('电影上线成功！');
                        location.href = '/movie/movielist.html';
                    }
                })
            })
    })




    function cateinit() {
        $.ajax({
            type: 'GET',
            url: '/my/movie/cate',
            success: function(res) {
                if (res.status != 0) {
                    return layui.layer.msg('获取分类信息失败!');
                }
                var htmlStr = template('tql-cate', res.data);
                $('[name="cate_id"]').html(htmlStr);
                layui.form.render();
            }
        })
    }
})